package info.maxhis.bn.birthday;

import info.maxhis.bn.ContactsAdapter;
import info.maxhis.bn.R;
import info.maxhis.entity.Friend;
import info.maxhis.service.FriendService;
import info.maxhis.util.CalendarUtil;
import info.maxhis.util.SharedData;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class EditBirthdayActivity extends Activity implements OnCheckedChangeListener  {
	private AutoCompleteTextView nameView;
	private EditText phoneNumView;
	private DatePicker datePicker;
	private Button saveButton;
	private FriendService fs;
	private String fId;
	private Friend f;
	private Resources rs;
	private RadioGroup dateTypeGroup;
	private Cursor cursor;
	private ContactsAdapter cAdapter;
	private SharedData share;
	private int dateType = CalendarUtil.DATE_TYPE_SOLAR;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_edit_birthday);
		rs = getResources();
		fs = new FriendService(this);
		share = new SharedData(this);
		fId = share.getFriendId();
		f = fs.findFriendById(fId);
		setTitle(R.string.title_edit_birthday);
		findViews();
		bindViews();
		autoComplete();
	}

	/**
	 * 自动补充姓名和号码
	 */
	private void autoComplete() {
		ContentResolver resolver = getContentResolver();
		cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, AddBirthdayActivity.PEOPLE_PROJECTION, null, null, "");
		cAdapter = new ContactsAdapter(this, cursor);
		nameView.setAdapter(cAdapter);
		nameView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/* 取得Cursor */
				Cursor c = cAdapter.getCursor();
				/* 移到所点击的位置 */
				c.moveToPosition(position);
				String number = c.getString(c
						.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
				
				number = (number == null ? "" : number);
				phoneNumView.setText(number);
			}
			
		});
	}
	
	private void bindViews() {
		//设置初始值
		nameView.setText(f.getName());
		phoneNumView.setText(f.getPhone());
		datePicker.init(f.getBirthYear(), f.getBirthMonth()-1, f.getBirthDay(), null);
		dateType = f.getDateType();
		if (dateType == CalendarUtil.DATE_TYPE_SOLAR) {
			RadioButton normalButton = (RadioButton) findViewById(R.id.normal_date);
			normalButton.setChecked(true);
		} else {
			RadioButton chineseButton = (RadioButton) findViewById(R.id.chinese_date);
			chineseButton.setChecked(true);
			
		}
		
		//保存数据
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String nameStr = nameView.getText().toString().trim();
				if (nameStr == null || nameStr.equals("")) {
					nameView.setError(getResources().getString(R.string.name_needed));
//					Toast.makeText(EditBirthdayActivity.this, R.string.name_needed, Toast.LENGTH_SHORT).show();
					return ;
				}
				String phone = phoneNumView.getText().toString().trim();
				f.setName(nameStr);
				f.setPhone(phone);
				f.setBirthYear(datePicker.getYear());
				f.setBirthMonth(datePicker.getMonth()+1);
				f.setBirthDay(datePicker.getDayOfMonth());
				f.setDateType(dateType);
				
				if (fs.updateFriend(f)) {
					//检查是否当天生日,若是，产生提醒
					if (CalendarUtil.daysLeft2Birthday(f) - share.getAdvanceTime() <= 0) {
						share.makeNotification(f);
					}
					AlertDialog.Builder builder = new AlertDialog.Builder(EditBirthdayActivity.this);
					builder.setMessage(rs.getString(R.string.update_success))
							.setCancelable(false)
							.setIcon(R.drawable.info).setTitle(rs.getString(R.string.notice))
							.setPositiveButton(rs.getString(R.string.confern), new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									Intent intent = new Intent(EditBirthdayActivity.this, BirthdayListActivity.class);
									startActivity(intent);
									finish();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
	}

	private void findViews() {
		nameView = (AutoCompleteTextView) findViewById(R.id.friend_name);
		phoneNumView = (EditText) findViewById(R.id.phone_num);
		saveButton = (Button) findViewById(R.id.edit_birthday);
		datePicker = (DatePicker) findViewById(R.id.birthday_date_picker);
		dateTypeGroup = (RadioGroup) findViewById(R.id.dateTypeGroup);
		dateTypeGroup.setOnCheckedChangeListener(this);
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if (checkedId == R.id.normal_date) {
			dateType = CalendarUtil.DATE_TYPE_SOLAR;
		} else {
			dateType = CalendarUtil.DATE_TYPE_LUNDAR;
		}
	}
}
